package com.kolon.business.mngr.service.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.kolon.business.mngr.service.dao.ServiceDao;
import com.kolon.framework.constant.Constant;
import com.kolon.framework.file.DefaultFileRenamePolicy;
import com.kolon.framework.file.FileUtil;
import com.kolon.framework.file.UploadedFile;
import com.kolon.framework.interfaces.SimpleController;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.MsgUtil;

@Controller("com.kolon.business.mngr.service.controller.ServiceWriteController")
public class ServiceWriteController implements SimpleController {

	@Resource(name="com.kolon.business.mngr.service.dao.ServiceDaoImpl")
	private ServiceDao serviceDao;
	
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="/business/mngr/service/serviceWrite.do")
	public ModelAndView controller(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Map<String, String> map = new HashMap<String, String>();
		List<UploadedFile> fileList = new ArrayList<UploadedFile>();
		UploadedFile imgFile = null;
		// 파라미터
		String servTp = multiRequest.getParameter("servTp");
		String fdrNm = multiRequest.getParameter("fdrNm");
		// 클라이언트 앱 디렉토리와 같을 시 예외처리
		if (Constant.APP_CNT_NM.equals(fdrNm))
			return new ModelAndView("redirect:/business/mngr/service/serviceList.do");
		map.put("servNm", ComUtil.nullChk(multiRequest.getParameter("servNm"), "없음"));
		map.put("servTp", servTp);
		map.put("servDesc", multiRequest.getParameter("servDesc"));
		map.put("lnkUrl", multiRequest.getParameter("lnkUrl"));
		map.put("tagNm", multiRequest.getParameter("tagNm"));
		map.put("fdrNm", fdrNm);
		map.put("cpyCd", "A".equals(multiRequest.getParameter("cpyCd")) ? null : "B");
		map.put("sortNum", multiRequest.getParameter("sortNum"));
		map.put("useYn", ComUtil.nullChk(multiRequest.getParameter("useYn"), "Y"));
		map.put("exYn", multiRequest.getParameter("exYn"));
		map.put("frfTp", ComUtil.getFrfTp(multiRequest.getParameter("servTp")));
		map.put("frfVer", multiRequest.getParameter("frfVer"));
		map.put("appNm", multiRequest.getParameter("appNm"));
		map.put("appDesc", ComUtil.nullChk(multiRequest.getParameter("appDesc")));
		// 회원 세션 정보
		HttpSession httpSession = multiRequest.getSession();
		Map userMap = (Map)httpSession.getAttribute(Constant.SESSION_MNGR_INFO);
		map.put("rgstId", (String)userMap.get("MNGR_ID"));
		// 아이콘 및 앱 파일 저장 경로
		String servIconPath = MsgUtil.getMessage("service.icon.path");
		String appFilePath = MsgUtil.getMessage("app.file.path");
		appFilePath = appFilePath + map.get("frfTp").toLowerCase() + File.separator + fdrNm + File.separator;
		// 웹이 아닐 시 중복 체크 함
		if (!"A".equals(servTp)) {
			if (serviceDao.getAppNmCnt(map) > 0)
				return new ModelAndView("redirect:/business/mngr/service/serviceList.do");
			if (serviceDao.getFdrNmCnt(map) > 0)
				return new ModelAndView("redirect:/business/mngr/service/serviceList.do");
			if (serviceDao.getAppVerCnt(map) > 0)
				return new ModelAndView("redirect:/business/mngr/service/serviceList.do");
		}
		// STEP START
		try {
			// STEP 01. 이미지 파일 업로드
			imgFile = FileUtil.fileUpload(multiRequest.getFile("imgNm"), servIconPath, 
					new DefaultFileRenamePolicy());
			map.put("imgNm", imgFile.getFileName());
			// STEP 02. 앱 파일 업로드
			for (int i=1; i<=3; i++) {
				UploadedFile uploadedFile = FileUtil.fileUpload(multiRequest.getFile("appFile"+i), 
						appFilePath, new DefaultFileRenamePolicy());
				map.put("fileRNm"+i, uploadedFile.getFileRealName());
				map.put("fileSNm"+i, uploadedFile.getFileName());
				map.put("fileTp"+i, uploadedFile.getExtension());
				map.put("fileSize"+i, String.valueOf(uploadedFile.getSize()));
				fileList.add(uploadedFile);
			}
			// STEP 03. 서비스 시퀀스 값 조회
			map.put("servNo", ComUtil.oTos(serviceDao.getMax().get("SERV_NO")));
			// STEP 04. 서비스 정보 등록
			serviceDao.insert(map);
		} catch (Exception e) {
			// 예외 발생 시 업로드 된 파일을 삭제
			if (imgFile != null)
				FileUtil.delFile(servIconPath + imgFile.getFileName());
			for (int i=0, size=fileList.size(); i<size; i++)
				FileUtil.delFile(appFilePath + fileList.get(i).getFileName());
		}
		// 리턴
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("redirect:/business/mngr/service/serviceList.do");
		return modelAndView;
	}
}
